<?php

declare (strict_types = 1);

namespace app\service\admin\system;

use app\model\system\DeptModel;
use own\auth\User;

class DeptService
{
    /**
     * 列表
     * @param array $param
     */
    public function getList(array $param)
    {
        $map = [];
        // 部门名称
        if($name = $param['name'] ?? '') {
            $map[] = ['name', 'like', '%'.trim($name).'%'];
        }
        // 负责人
        if($leader = $param['leader'] ?? '') {
            $map[] = ['leader', 'like', '%'.trim($leader).'%'];
        }
        // 联系电话
        if($phone = $param['phone'] ?? '') {
            $map[] = ['phone', 'like', '%'.trim($phone).'%'];
        }
        $list = DeptModel::where($map)->order('sort asc')->select()->toArray();
        return recursion($list, 0, false, 'parent_id');
    }
    /**
     * 编辑
     * @param array $data
     * @param integer $id
     */
    public function edit(array $data, int $id): bool
    {
        if($id) {
            $dept = DeptModel::find($data['id']);
            if(!$dept) {
                tips('无部门信息');
            }
            $dept->updated_by = make(User::class)->getUser();
        } else {
            $dept = new DeptModel();
            $dept->created_by = make(User::class)->getUser();
        }
        $dept->parent_id = $data['parent_id'];
        $dept->name = trim($data['name']);
        $dept->leader = trim($data['leader']);
        $dept->phone = trim($data['phone']);
        $dept->status = $data['status'];
        $dept->sort = $data['sort'];
        $dept->remark = $data['remark'];
        return $dept->save() ? true : false;
    }
    /**
     * 删除
     * @param integer $id
     */
    public function delete(int $id)
    {
        return DeptModel::where('id', $id)->delete() ? true : false;
    }
}